<template>
  <view class="page">
    <uv-navbar title="任务大厅" placeholder bg-color="transparent" left-icon="" />
    <view class="fixbox">
      <view
        class="tab-row ss-white ss-size ss-p-24 ss-flex ss-col-center ss-row-center"
        @click="regionShow"
      >
        <uv-icon name="map-fill" color="#fff" size="18" class="ss-m-x-18"></uv-icon>
        <view class="ss-font-28">
          {{ province || "省" }}-{{ city || "市" }}-{{ district || "区/县" }}
        </view>
      </view>
    </view>
    <view class="task-box">
      <scroll-view
        scroll-y
        :scroll-into-view="scrollTop"
        scroll-with-animation
        :lower-threshold="0"
        class="task-list"
        @scroll="scrollTop = ''"
        @scrolltolower="scrolltolower"
      >
        <g-tabs
          :tabs="typeList"
          class="tabBox"
          key-value="value"
          :active="queryParams.type"
          @change="changeTab"
        />
        <view
          class="task-item"
          v-for="(item, index) in dataList"
          :id="'task' + index"
          :key="index"
          @click="handleDetail(item)"
        >
          <view class="ss-flex ss-p-y-22 ss-p-x-30">
            <view class="ss-m-x-16">
              <image v-if="item.imgUrl" :src="webSrc(item.imgList[0])" class="imgLeft" />
            </view>
            <view>
              <view class="ss-line-1">
                <view class="tag" v-if="item.type == 1" text="" type="error">急</view>
                {{ item.projectName + ' ' + item.workOrderTitle }}
              </view>
              <uv-text
                :text="item.systemName"
                color="#4EA770"
                size="24rpx"
                line-height="54rpx"
              />
              <uv-text
                :text="`位置：${item.positionDescription}`"
                color="#757575"
                size="24rpx"
                line-height="34rpx"
              />
              <uv-text
                :text="`设备：${item.deviceDescription}`"
                color="#757575"
                size="24rpx"
                line-height="34rpx"
              />
              <uv-text
                :text="item.createTime"
                color="#757575"
                size="24rpx"
                line-height="40rpx"
              />
            </view>
          </view>
        </view>
        <uv-load-more v-if="dataList.length > 0" :status="status" line />
      </scroll-view>
    </view>
    <uv-picker
      ref="regionRef"
      :columns="regionList"
      key-name="name"
      :default-index="regionIndex"
      @confirm="confirmRegion"
      @change="changeRegion"
    />
  </view>
</template>
<script setup>
import { onMounted, reactive, ref, watch, onBeforeUnmount } from "vue";
import { taskHall, getRegionData } from "@/request/task.js";
import { webSrc } from "@/common/mothed.js";

const props = defineProps({
  // 是否下拉刷新
  refresh: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["update:refresh"]);

watch(
  props,
  (v) => {
    if (v.refresh) {
      setTimeout(() => {
        queryParams.pageNum = 1;
        scrollTop.value = "task0";
        getList();
      }, 0);
    }
  },
  { immediate: true, deep: true }
);

const dataList = ref([]); // 数据列表
const queryParams = reactive({
  regionId: "", // 区域ID
  type: null, // 任务类别
  pageNum: 1, // 页数
  pageSize: 10, // 条数
});
const regionRef = ref(); // 地区选择器
const regionList = ref([]); // 地区列表
const allRegionList = ref([]); // 所有地区列表
const regionIndex = ref([0, 0, 0]); // 地区索引
const province = ref(""); // 省
const city = ref(""); // 市
const district = ref(""); // 区县
const total = ref(0); // 总条数
const status = ref("loadmore");
const scrollTop = ref("task0"); // 滚动位置
const typeList = ref([
  { label: "全部", value: null },
  { label: "加急工单", value: "1" },
  { label: "普通工单", value: "2" },
]); // 任务类别

onMounted(async () => {
  await getRegionList();
  setTimeout(() => {
    getLocationInfo();
    uni.$on("task", () => {
      getList();
    });
  }, 0);
});

onBeforeUnmount(() => {
  uni.$off("task");
});

// 获取当前位置信息
const getLocationInfo = () => {
  uni.getLocation({
    type: "gcj02",
    // #ifdef APP-PLUS
    geocode: true,
    // #endif
    success: (res) => {
      console.log("执行获取地址", res);
      // #ifdef APP-PLUS
      if (res.address) {
        province.value = res.address.province;
        city.value = res.address.city;
        district.value = res.address.district;
        queryParams.regionId = findDistrictId(province.value, city.value, district.value);
        getList();
      }
      // #endif
      // #ifdef H5
      getList();
      // #endif
    },
    fail: (e) => {
      console.log("获取位置失败", e);
      setTimeout(() => {
        getLocationInfo();
      }, 1000);
    },
  });
};

// 查找区县ID
const findDistrictId = (province, city, district) => {
  let tree = allRegionList.value || [];
  if (!tree.length) return null;
  let frist = allRegionList.value.find((i) => i.name == province);
  let pindex = allRegionList.value.findIndex((i) => i.name == province) || 0;
  if (!frist) return null;
  let second = frist ? frist.children.find((i) => i.name == city) : null;
  let cindex = frist ? frist.children.findIndex((i) => i.name == city) : 0;
  if (!second) return null;
  let third = second ? second.children.find((i) => i.name == district) : null;
  let dindex = second ? second.children.findIndex((i) => i.name == district) : 0;
  regionIndex.value = [pindex, cindex, dindex];
  regionList.value = [tree, frist.children, second.children];
  return third ? third.id : null;
};

// 获取地区列表
const getRegionList = async () => {
  await getRegionData().then((res) => {
    if (res.code == 200) {
      allRegionList.value = res.data;
      let provinceList = res.data;
      if (provinceList.length > 0) {
        let cityList = provinceList[0].children;
        if (cityList.length > 0) {
          let districtList = cityList[0].children;
          if (districtList.length > 0) {
            regionList.value = [provinceList, cityList, districtList];
          } else {
            regionList.value = [provinceList, cityList];
          }
        } else {
          regionList.value = [provinceList];
        }
      }
    }
  });
};

// 显示区域列表
const regionShow = () => {
  regionRef.value.open();
};

// 切换区域
const changeRegion = (e) => {
  console.log(e);
  let proList = allRegionList.value;
  console.log("省列表", proList);
  let cityList = proList[e.indexs[0]].children;
  console.log("市列表", cityList);
  let disList = cityList[e.indexs[1]].children;
  console.log("区县列表", disList);

  if (e.columnIndex == 0) {
    regionIndex.value = [e.indexs[0], 0, 0];
  } else if (e.columnIndex == 1) {
    regionIndex.value = [e.indexs[0], e.indexs[1], 0];
  }
  regionList.value = [proList, cityList, disList];
};

// 确认区域
const confirmRegion = (e) => {
  console.log(e);
  province.value = e.value[0].name;
  city.value = e.value[1].name;
  district.value = e.value[2].name;
  queryParams.regionId = e.value[2].id;
  queryParams.pageNum = 1;
  getList();
};

// 切换工单状态
const changeTab = (val) => {
  queryParams.type = val.value;
  queryParams.pageNum = 1;
  getList();
};

// 获取数据列表
const getList = () => {
  status.value = "loading";
  taskHall(queryParams)
    .then((res) => {
      if (res.code == 200) {
        let list = res.rows.map((i) => {
          return {
            ...i,
            imgList: i.imgUrl ? i.imgUrl.split(",") : [],
          };
        });
        dataList.value = queryParams.pageNum == 1 ? list : dataList.value.concat(list);
        total.value = res.total;
      }
    })
    .finally(() => {
      emit("update:refresh", false);
      uni.stopPullDownRefresh();
      status.value = total.value == dataList.value.length ? "nomore" : "loadmore";
    });
};

// 加载更多
const scrolltolower = () => {
  if (total.value > dataList.value.length) {
    queryParams.pageNum += 1;
    getList();
  }
};

// 项目详情
const handleDetail = (item) => {
  uni.navigateTo({
    url: `/pages/Task/taskDetails?id=${item.workOrderId}`,
  });
};
</script>
<style lang="scss" scoped>
.page {
  width: 100vw;
  background: linear-gradient(180deg, #ffffff, #50bc7a);
  padding: 0;
  height: 100vh;
  margin: 0;
}

.fixbox {
  width: 100%;
  box-sizing: border-box;
  padding-top: 60rpx;
  background: linear-gradient(to top, #edf7f1, #fbfdfc);
  background-size: 100% 100%;

  .tab-row {
    background-size: 100% 100%;
    width: 80%;
    text-align: center;
    height: 90rpx;
    margin: 0 auto;
    border-top-left-radius: 20rpx;
    border-top-right-radius: 20rpx;
    background: linear-gradient(to right, #4c9f6a, #6fcd91);
  }
}

.task-box {
  height: 75vh;
  width: 90vw;
  margin: 30rpx auto;
  margin-top: 0;
  box-sizing: border-box;

  .task-list {
    width: 100%;
    height: 100%;
    background: #fff;
    box-shadow: 0 0 20rpx 2rpx rgba(78, 167, 112, 0.16);
    border-radius: 20rpx;
    box-sizing: border-box;
    padding: 20rpx;
    .task-item {
      margin-bottom: 20rpx;
      width: auto;
      min-height: 160rpx;
      background: #f6f6f6;
      border-radius: 20rpx;
      justify-content: space-between;
      margin-bottom: 20rpx;
      box-sizing: border-box;
      overflow: hidden;
      position: relative;

      .imgLeft {
        width: 180rpx;
        height: 230rpx;
      }
      .tag {
        display: inline-block;
        padding: 0 8rpx;
        border-radius: 6rpx;
        color: #fff;
        background-color: #f56c6c;
        font-size: 24rpx;
        height: 44rpx;
        line-height: 44rpx;
        vertical-align: middle;
      }
      .below {
        position: absolute;
        top: 81rpx;
        left: 320rpx;
        color: #e21818;
        font-size: 24rpx;
      }

      &::after {
        content: "";
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        width: 20rpx;
        background: #85c889;
      }

      .row {
        margin-top: 12rpx;
        display: flex;

        > view:first-child {
          margin-right: 40rpx;
        }
      }
    }
  }
}
</style>
